package com.choosefine.it.basedata.service;

import com.choosefine.it.basedata.dao.TeamTypeClassMapper;
import com.choosefine.it.basedata.model.TeamTypeClass;
import com.choosefine.it.basedata.model.vo.TeamTypeClassFindVO;
import com.choosefine.it.common.def.CommonConstant;
import com.choosefine.it.common.def.ResultCode;
import com.choosefine.it.common.exception.BusinessException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 
 * @author guwenwei
 */
@Service("teamtypeClassService")
public class TeamTypeClassService {

	@Resource
	private TeamTypeClassMapper teamTypeClassMapper;
	
	/**
	 * 第二版用户排序——修改
	 * 
	 * update by juchengyang 2017/2/16
	 */
	public int deleteByPrimaryKey(Integer id) {
		int num = 0;
		TeamTypeClass deleteTeamTypeClassUp = teamTypeClassMapper.selectTeamTypeClassBySortNum(id);
		TeamTypeClass deleteTeamTypeClass = teamTypeClassMapper.selectByPrimaryKey(id);
		if(null != deleteTeamTypeClassUp){
			deleteTeamTypeClassUp.setSortNum(deleteTeamTypeClass.getSortNum());
			num += teamTypeClassMapper.updateByPrimaryKeySelective(deleteTeamTypeClassUp);
		}
		num += teamTypeClassMapper.deleteByPrimaryKey(id);
		return num;
	}

	/**
	 * 第二版用户排序——修改
	 * 
	 * update by juchengyang 2017/2/16
	 * @throws BusinessException 
	 */
	public int insert(TeamTypeClass record) throws BusinessException {
		//数据唯一校验
		int count = teamTypeClassMapper.checkTeamTypeInsert(record.getClassname());
		if(count != 0){
			throw new BusinessException(ResultCode.FAILED,CommonConstant.IS_EXISTS);
		}
		int num = 0;
		TeamTypeClass lastTeamTypeClass = teamTypeClassMapper.selectTeamTypeClassBySortNum(0);
		if(null != lastTeamTypeClass){
			record.setSortNum(-1);
			num += teamTypeClassMapper.insert(record);
			record = teamTypeClassMapper.selectTeamTypeClassBySortNum(-1);
			lastTeamTypeClass.setSortNum(record.getId());
			record.setSortNum(0);
			num += teamTypeClassMapper.updateByPrimaryKeySelective(record);
			num += teamTypeClassMapper.updateByPrimaryKeySelective(lastTeamTypeClass);
		}else{
			record.setSortNum(0);
			num += teamTypeClassMapper.insert(record);
		}
		return num;
	}

	public int update(TeamTypeClass record) throws BusinessException {
		//数据唯一校验
		int count = teamTypeClassMapper.checkTeamTypeInsert(record.getClassname());
		if(count != 0){
			throw new BusinessException(ResultCode.FAILED,CommonConstant.IS_EXISTS);
		}
		return teamTypeClassMapper.updateByPrimaryKey(record);
	}
	
	public TeamTypeClass findByPrimaryKey(Integer id) {
		
		return teamTypeClassMapper.selectByPrimaryKey(id);
	}

	public List<TeamTypeClass> selectAll() {

		return teamTypeClassMapper.selectAll();
	}

	public TeamTypeClass getTeamTypeClassByName(String typeclassname){
		return teamTypeClassMapper.selectTeamTypeClassByName(typeclassname);
	}
	
	public PageInfo<TeamTypeClass> selectTeamTypeClassByName(String typeclassname, Integer pageNum, Integer pageSize){
		pageNum = pageNum == null?1:pageNum;
		pageSize = pageSize == null?10:pageSize;
		PageHelper.startPage(pageNum, pageSize);
		return new PageInfo<TeamTypeClass>(teamTypeClassMapper.getTeamTypeClassByName(typeclassname));
	}
	
	public List<TeamTypeClass> findAllByPage() throws BusinessException {
		
		//查询数据库返回列表
		List<TeamTypeClass> getList = teamTypeClassMapper.selectAll();
		if(getList.size()==0){
			return new ArrayList<TeamTypeClass>();
		}
		//数据校验
		checkList(getList);
		int size = getList.size();
		List<TeamTypeClass> returnList = new ArrayList<>();
		for(TeamTypeClass temp:getList){
			//最后一位 sortNum 为0
			if(0 == temp.getSortNum()){
				returnList.add(temp);
			}
		}
		TeamTypeClass tempTeamTypeClass = returnList.get(0);
		while(returnList.size()<size){
			for(int i = 0; i<size; i++){
				if(tempTeamTypeClass.getId().equals(getList.get(i).getSortNum())){
					returnList.add(getList.get(i));
					tempTeamTypeClass = getList.get(i);
				}
			}
		}
		for(int i=0; i<size/2; i++){
			TeamTypeClass tempProjecType = returnList.get(i);
			returnList.set(i, returnList.get(size-i-1));
			returnList.set(size-i-1, tempProjecType);
		}
		return returnList;
	}
	/**
	 * 排序用
	 *  juchengyang 2017年2月16日
	 */
	public int teamTypeClassOrderUp(Integer fromId,Integer toId){
		int num = 0;
		TeamTypeClass fromTeamTypeClass = null;
		TeamTypeClass fromTeamTypeClassUp = null;
		TeamTypeClass toTeamTypeClassUp = null;
		fromTeamTypeClass = teamTypeClassMapper.selectByPrimaryKey(fromId);
		fromTeamTypeClassUp = teamTypeClassMapper.selectTeamTypeClassBySortNum(fromId);
		toTeamTypeClassUp = teamTypeClassMapper.selectTeamTypeClassBySortNum(toId);
		if(toTeamTypeClassUp == null){
			fromTeamTypeClassUp.setSortNum(fromTeamTypeClass.getSortNum());
			fromTeamTypeClass.setSortNum(toId);
		}else{
			fromTeamTypeClassUp.setSortNum(fromTeamTypeClass.getSortNum());
			fromTeamTypeClass.setSortNum(toId);
			toTeamTypeClassUp.setSortNum(fromId);
		}
		if(null != toTeamTypeClassUp){
			num += teamTypeClassMapper.updateByPrimaryKeySelective(toTeamTypeClassUp);
		}
		num += teamTypeClassMapper.updateByPrimaryKeySelective(fromTeamTypeClass);
		num += teamTypeClassMapper.updateByPrimaryKeySelective(fromTeamTypeClassUp);
		return num;
	}
	public int teamTypeClassOrderDown(Integer fromId,Integer toId){
		int num = 0;
		TeamTypeClass fromTeamTypeClass = null;
		TeamTypeClass fromTeamTypeClassUp = null;
		TeamTypeClass toTeamTypeClass = null;
		fromTeamTypeClass = teamTypeClassMapper.selectByPrimaryKey(fromId);
		fromTeamTypeClassUp = teamTypeClassMapper.selectTeamTypeClassBySortNum(fromId);
		toTeamTypeClass = teamTypeClassMapper.selectByPrimaryKey(toId);
		if(fromTeamTypeClassUp == null){
			fromTeamTypeClass.setSortNum(toTeamTypeClass.getSortNum());
			toTeamTypeClass.setSortNum(fromId);
		}else{
			fromTeamTypeClassUp.setSortNum(fromTeamTypeClass.getSortNum());
			fromTeamTypeClass.setSortNum(toTeamTypeClass.getSortNum());
			toTeamTypeClass.setSortNum(fromId);
		}
		if(null != fromTeamTypeClassUp){
			num += teamTypeClassMapper.updateByPrimaryKeySelective(fromTeamTypeClassUp);
		}
		num += teamTypeClassMapper.updateByPrimaryKeySelective(fromTeamTypeClass);
		num += teamTypeClassMapper.updateByPrimaryKeySelective(toTeamTypeClass);
		return num;
	}
	
	/*
	 * 数据校验
	 */
	public void checkList (List<TeamTypeClass> list) throws BusinessException{
    	Map<Integer, Integer> keyMap = new HashMap<Integer, Integer>();
        Map<Integer, Integer> nextMap = new HashMap<Integer, Integer>();
        for( TeamTypeClass n: list){
        	if (nextMap.containsKey(n.getSortNum())) {
        		throw new BusinessException(ResultCode.FAILED,CommonConstant.DATA_NEXT);
//                logger.info("数据出错：next重复");
            }
        	if (n.getSortNum().equals(n.getId())) {
        		throw new BusinessException(ResultCode.FAILED,CommonConstant.DATA_NEXT);
//                logger.info("数据出错：指向自己");
            }
        	keyMap.put(n.getId(), n.getSortNum());
            nextMap.put(n.getSortNum(), 0);
        }
        if(!nextMap.containsKey(0)){
        	throw new BusinessException(ResultCode.FAILED,CommonConstant.DATA_NEXT);
//        	logger.info("数据出错：不存在0（最后一位标识）");
        }
        for (TeamTypeClass n : list) {
            Integer next = keyMap.get(n.getId());
            if (next.equals(0)) {
            	if(!nextMap.containsKey(n.getId()) && nextMap.size()>1){
            		throw new BusinessException(ResultCode.FAILED,CommonConstant.DATA_NEXT);
//            		logger.info("没有指向最后一位的");
            	}
            	if(nextMap.get(next).equals(1)){
            		throw new BusinessException(ResultCode.FAILED,CommonConstant.DATA_NEXT);
//            		logger.info("数据出错，最后一位不唯一");
            	}else{
            		nextMap.put(next, 1);
            	}
            	
            } else {
            	if(keyMap.containsKey(next)){
	            	if(nextMap.get(next).equals(1)){
	            		throw new BusinessException(ResultCode.FAILED,CommonConstant.DATA_NEXT);
//	            		logger.info("数据出错，"+next+"重复");
	            	}else{
	            		nextMap.put(next, 1);
	            	}
            	}else{
            		throw new BusinessException(ResultCode.FAILED,CommonConstant.DATA_NEXT);
//            		logger.info(next+" 没有对应的 id");
            	}
            }

        }
        if(nextMap.containsValue(0)){
        	throw new BusinessException(ResultCode.FAILED,CommonConstant.DATA_NEXT);
//        	logger.info("next 有无效值");
        }
    }

	/**
     * 
     * @Description：查询所有班组类目
     * @Author：chenjian
     * @Create Date：2017年2月18日
     * @param：
     * @return：
     */
	public List<TeamTypeClassFindVO> getTeamTypeFirstList() {
		return teamTypeClassMapper.getTeamTypeFirstList();
	}

}
